import React, { Component, Fragment } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { uploadUrl } from '@/config/index'
import {
  Card,
  message,
  Button,
  Table,
  Select,
  Modal,
  Form,
  Input,
  Icon,
  Upload,
  Popconfirm,
  DatePicker
} from 'antd'
import { connect } from 'dva'
import {LZFormItem} from "@/components/LZForm";
import moment from "moment";
import commonService from "@/services/common";
import {getToken} from "@/utils/localStorage";
import {router} from "umi";
import SpikeService from "./services";
import AddProducts from './addProducts'

const { Option } = Select
const { RangePicker } = DatePicker;
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 21 },
  },
}

@connect()
@Form.create()
class SpikeDetail extends Component {
  state = {
    id: '',
    tabVisible: false, // modal的控制
    imgVisible: false,
    title: '',// modal的标题
    imgSrc: '',
    fileList: [],
    pageNumber: 1,
    pageSize: 10,
    addProductVisible: false,
    tabProductVisible: false,
    loading: true,
    confirmLoading: false,
    channelData: [],
    detail: {},
    tabs: []
  }
  
  columns = [
    {
      title: '商品ID',
      dataIndex: 'productId',
      align: 'center',
      width: 100,
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      align: 'center',
      width: 100
    },
    {
      title: 'SKUID',
      dataIndex: 'skuId',
      align: 'center',
      width: 100
    },
    {
      title: '规格',
      dataIndex: 'skuSpe',
      align: 'center',
      width: 100
    },
    {
      title: '租期',
      dataIndex: 'days',
      align: 'center',
      width: 80,
    },
    {
      title: '商品价格',
      dataIndex: 'originPrice',
      align: 'center',
      width: 100,
      render: (text, record) => {
        return `${text}元/天`
      }
    },
    {
      title: '限时价格',
      dataIndex: 'price',
      align: 'center',
      render: (text) => {
        return `${text  }元/天`
      }
    },
    {
      title: '库存',
      dataIndex: 'inventory',
      align: 'center',
    },
    {
      title: '展示标签',
      dataIndex: 'lable',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => (
        <div className="table-action">
          <Popconfirm
            title='确定要删除吗？'
            onConfirm={() => this.deleteProduct(record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      )
    },

  ]
  
  componentDidMount() {
    const {match: {params: { id }}} = this.props;
    this.getDetail(id);
    this.getTabList()
  }
  
  getDetail = (id) => {
    this.setState({
      loading: true
    });
    SpikeService.getSpikeSpecialPageDetail({
      indexId: id,
      type: 'SPIKE'
    }).then(res => {
      let fileList = []
      let detail = {}
      if (res.responseType === 'SUCCESS' && !res.data) {
        fileList = []
      } else {
        fileList = [
          {uid: res.id, url: res.adPic}
        ]
        detail = res
      }
      this.setState({
        id,
        detail,
        fileList
      });
    }).finally(() => {
      this.setState({
        loading: false
      });
    })
  }
  
  getTabList = () => {
    commonService.getTabList().then(res => {
      this.setState({
        tabs: res
      });
    })
  }
  
  // modal的确认
  handleOk = () => {
    this.props.form.validateFields((err, value) => {
      if (!err) {
        this.setState({
          confirmLoading: true
        })
        const {imgSrc, id, detail} = this.state
        const format = 'YYYY-MM-DD HH:mm:ss'
        value.adPic = imgSrc || detail.adPic;
        value.startTime = moment(value.activityTime[0]).format(format)
        value.endTime = moment(value.activityTime[1]).format(format)
        value.indexId = id
        value.id = detail.id
        value.showTab = value.showTab.join('&')
        value.specialroducts = detail.specialroducts
        SpikeService.saveSpikeSpecialPage({
          ...value,
        }).then(res => {
          message.success('保存成功')
          router.push('/configure/spike')
          console.log(res);
        }).finally(() => {
          this.setState({
            confirmLoading: false
          });
        })
      }
    })
  }
  
  // 上传的回调
  handleUploadChange = ({ file, fileList, event }) => {
    const filelist = [...fileList] || [];
    if (file.status === 'done') {
      filelist.map(item => {
        const imgSrc = item.response.data
        if (!imgSrc) {
          message.error('上传失败，token失效')
        }
        this.setState({
          imgSrc,
        })
      })
    }
    this.setState({
      fileList,
    })
  }

  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true,
    });
  }
  
  // 上传后删除的回调
  onRemove = () => {
    this.setState(
      {
        fileList: [],
        imgSrc: '',
      })
  }
  
  deleteProduct = (record) => {
    const { detail } = this.state
    const { specialroducts, } = detail;
    const index = specialroducts.findIndex(f=> f.productId === record.productId)
    specialroducts.splice(index, 1)
    this.setState({
      detail: {
        ...detail,
        specialroducts
      }
    });
  }
  
  selectProducts = (rows) => {
    const { detail } = this.state
    const _rows = rows.map(v=>{
      return {
        ...v,
        ...v.cyclePrices[0],
        indexId: this.state.id,
        originPrice: v.cyclePrices[0].price,
        price: v.price,
      }
    })
    let specialroducts = detail.specialroducts ? detail.specialroducts : []
    specialroducts = specialroducts.concat(_rows)
    this.setState({
      addProductVisible: false,
      detail: {
        ...this.state.detail,
        specialroducts
      }
    });
  }
  
  // 添加产品
  addProduct = () => {
    this.setState({
      addProductVisible: true
    })
  }

  handleProductCancel = () => {
    this.setState({
      addProductVisible: false
    })
  }
  
  cancel = ()=>{
    router.push('/configure/spike')
  }
  
  render() {
    const { loading,confirmLoading, addProductVisible,imgVisible, imgSrc, fileList, detail, tabs } = this.state;
    const { title, adPic, showTab, specialroducts = [], startTime, endTime } = detail;
    const { getFieldDecorator } = this.props.form
    let time = null
    if (startTime && endTime) {
      time = [moment(startTime), moment(endTime)]
    }
    const _showTabs = showTab && showTab.split('&').map(v=> Number(v)) || []
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    )
    const channelData =[
      { label: '秒杀专场',value: 1},
      { label: '主题专场',value: 2},
    ]
    
    return (
      <PageHeaderWrapper className="spike">
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Form {...formItemLayout}>
            <Form.Item label="专场类型">秒杀专场</Form.Item>
            <Form.Item label="专场标题">{title}</Form.Item>
            <Form.Item label="宣传图片">
              {getFieldDecorator('adPic', {
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      if (!value&&imgSrc) {
                        callback('图片不能为空');
                      }
                      callback();
                    },
                  },
                ],
                initialValue: imgSrc || adPic,
              })(
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  listType="picture-card"
                  headers={{
                    token: getToken()
                  }}
                  fileList={fileList}
                  onPreview={this.handlePreview} // 预览
                  onRemove={this.onRemove} // 删除
                  onDownload={this.onDownload}
                  onChange={this.handleUploadChange}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              )}
            </Form.Item>
            
            <LZFormItem field="activityTime" label="活动时间" initialValue={time}
                        getFieldDecorator={getFieldDecorator} required >
              <RangePicker
                className="w-400"
                showTime
                format="YYYY/MM/DD HH:mm:ss"
                placeholder={['开始时间', '结束时间']}
              />
            </LZFormItem>
            <Form.Item label="添加商品" required className="add-product">
              <Button type='primary' ghost className="w-80 mb-18" onClick={this.addProduct}>新增</Button>
              <Table
                columns={this.columns}
                dataSource={specialroducts}
                rowKey={record => record.id}
                pagination={false}
              />
            </Form.Item>
            <LZFormItem field="showTab" label="展示Tab" getFieldDecorator={getFieldDecorator}
                        className="mt-20 mb-18"
                        requiredMessage="展示Tab不能为空" initialValue={_showTabs}>
              <Select placeholder='请选择' mode="multiple" className="w-240">
                {tabs && tabs.map(item => (
                  <Option value={item.id} key={item.id}>{item.name}</Option>
                ))}
              </Select>
            </LZFormItem>
            <Form.Item wrapperCol={{offset: 3}}>
              <Button onClick={this.cancel}>取消</Button>
              <Button type="primary" onClick={this.handleOk} loading={confirmLoading}>确定</Button>

            </Form.Item>
    
          </Form>
        </Card>
  
        <AddProducts visible={addProductVisible} selectProducts={this.selectProducts}
                     type="spike"
                     scrollProductCancel={this.handleProductCancel}/>
  
        <Modal visible={imgVisible} footer={null}
          onCancel={() => this.setState({ imgVisible: false })}
          width={600}
        >
          <img src={imgSrc || detail.adPic} alt="" className="preview-img" />
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default SpikeDetail
